package com.wisdom.smartbook.activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;

import androidx.annotation.Nullable;

import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.github.barteksc.pdfviewer.listener.OnPageErrorListener;
import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle;
import com.shockwave.pdfium.PdfDocument;
import com.wisdom.smartbook.R;
import com.wisdom.smartbook.base.BaseActivity;
import com.wisdom.smartbook.listener.OnDownloadListener;
import com.wisdom.smartbook.utils.DialogTipsUtil;
import com.wisdom.smartbook.utils.DialogUtil;
import com.wisdom.smartbook.utils.DownloadUtil;
import com.wisdom.smartbook.utils.FileManager;
import com.wisdom.smartbook.utils.FileProviderHelper;
import com.wisdom.smartbook.utils.IntentUtil;
import com.wisdom.smartbook.utils.KLog;
import com.wisdom.smartbook.utils.SystemUtil;
import com.wisdom.smartbook.utils.ToastUtils;

import java.io.File;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * 文件预览
 */
public class FileBrowserActivity extends BaseActivity implements OnPageChangeListener, OnLoadCompleteListener,
        OnPageErrorListener {

    public String urtStr = "";
    public String fileName = "";
    private ExecutorService mExecutorService;
    private PDFView mPDFView;
    private int pageNumber = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
//        ImmersionBar.with(this).statusBarDarkFont(true, 0f) //原理：如果当前设备支持状态栏字体变色，会设置状态栏字体为黑色，如果当前设备不支持状态栏字体变色，会使当前状态栏加上透明度，否则不执行透明度
//                .init();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_file_browser;
    }

    protected void initView() {
        urtStr = getIntent().getStringExtra("urlStr");
        mPDFView = findViewById(R.id.pdfView);
    }

    @Override
    protected void initData() {
        mExecutorService = Executors.newSingleThreadExecutor();
        DialogUtil.showProgressDialog(this, "正在加载...");
        mExecutorService.execute(new Runnable() {
            @Override
            public void run() {
                downFile(urtStr);
            }
        });
    }


    /**
     * 文件下载
     */
    private void downFile(String url) {
        String temp = url;
        fileName = temp.substring(temp.lastIndexOf("/") + 1);
        DownloadUtil.get().download(url, FileManager.getFileCachePath(FileBrowserActivity.this), fileName,
                new OnDownloadListener() {
                    @Override
                    public void onDownloadSuccess(File file, boolean isNew) {
                        //下载完成进行相关逻辑操作
                        Message msg = mHandler.obtainMessage();
                        msg.what = 10;
                        msg.obj = file.getAbsolutePath();
                        mHandler.sendMessage(msg);
                    }

                    @Override
                    public void onDownloading(int progress) {
                        Message msg = mHandler.obtainMessage();
                        msg.what = 11;
                        msg.obj = progress;
                        mHandler.sendMessage(msg);
                    }

                    @Override
                    public void onDownloadFailed(Exception e) {
                        //下载异常进行相关提示操作
                        Message msg = mHandler.obtainMessage();
                        msg.what = 12;
                        msg.obj = e;
                        mHandler.sendMessage(msg);
                    }
                });
    }




    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 12) {
                DialogUtil.closeProgressDialog();
                ToastUtils.showShort("页面加载失败！");
                finish();
            } else if (msg.what == 10) {
                DialogUtil.closeProgressDialog();
                String filePath = (String) msg.obj;
                if (filePath.endsWith(".pdf")) {
                    displayPdfFromUri(filePath);
                } else {
                    try {
                        startActivityForResult(IntentUtil.getExcelFileIntent(mActivity, filePath), 10);
                    } catch (Exception e) {
                        e.printStackTrace();
                        ToastUtils.showLongSafe("设备暂不支持文件浏览服务");

                    }
                }
            }
        }
    };



    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10) {
            finish();
        }
    }

    String pdfFileName;

    private void displayPdfFromUri(String filePath) {

        mPDFView.fromFile(new File(filePath))
                .defaultPage(pageNumber)
                .onPageChange(this)
                .enableAnnotationRendering(true)
                .onLoad(this)
                .scrollHandle(new DefaultScrollHandle(this))
                .spacing(10) // in dp
                .onPageError(this)
                .load();
    }

    @Override
    public void onPageChanged(int page, int pageCount) {
        pageNumber = page;
        setTitle(String.format("%s %s / %s", pdfFileName, page + 1, pageCount));
    }

    @Override
    public void loadComplete(int nbPages) {
        PdfDocument.Meta meta = mPDFView.getDocumentMeta();
        KLog.e("title = " + meta.getTitle());
        KLog.e("author = " + meta.getAuthor());
        KLog.e("subject = " + meta.getSubject());
        KLog.e("keywords = " + meta.getKeywords());
        KLog.e("creator = " + meta.getCreator());
        KLog.e("producer = " + meta.getProducer());
        KLog.e("creationDate = " + meta.getCreationDate());
        KLog.e("modDate = " + meta.getModDate());

        printBookmarksTree(mPDFView.getTableOfContents(), "-");

    }

    @Override
    public void onPageError(int page, Throwable t) {
        KLog.e("Cannot load page " + page);
    }


    public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {
        for (PdfDocument.Bookmark b : tree) {

            KLog.e(String.format("%s %s, p %d", sep, b.getTitle(), b.getPageIdx()));

            if (b.hasChildren()) {
                printBookmarksTree(b.getChildren(), sep + "-");
            }
        }
    }
}